package com.my.study.utils;

import com.my.study.enums.BusinessExceptionEnum;
import com.my.study.exception.BusinessException;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.*;

public class XmlBeanUtil {

    public static Set<String> readValue(String fileName) {
        Set<String> stringSet = new HashSet<>();
        try {
            //实例化读取xml文件的对象
            SAXReader reader = new SAXReader();
            //设置文件路径,并将信息保存到一个Document对象中
            Document doc = reader.read(Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("security"+File.separator+"white_list.xml"));
            //获取xml的根标签
            Element root = doc.getRootElement();
            //获取根标签中所有名字为子标签的标签中的所有子子标签,并保存到一个List中
            List<Element> elements = root.elements();
            getSet(stringSet, elements);
        } catch (Exception e) {
            throw BusinessException.fail(BusinessExceptionEnum.FAIL.code, "xml文件读取失败");
        }
        return stringSet;
    }

    /**
     * 递归取值
     *
     * @param stringSet
     * @param elements
     */
    private static void getSet(Set<String> stringSet, List<Element> elements) {
        for(Element element:elements){
            if(element.elements().size()<1){
                stringSet.add(element.getStringValue());
            }
            getSet(stringSet,element.elements());
        }
    }

    /**
     * JavaBean转XML
     * @param bean - JavaBean
     * @return - XML
     */
    public static String toXml(Object bean) {
        return initXStream(bean.getClass()).toXML(bean);
    }

    /**
     * XML转JavaBean
     * @param xml - XML
     * @param beanClazz - JavaBean Class
     * @param <T>
     * @return - JavaBean
     */
    @SuppressWarnings("unchecked")
    public static <T> T fromXml(String xml, Class<T> beanClazz) {
        return (T) initXStream(beanClazz).fromXML(xml);
    }

    private static XStream initXStream(Class<?> beanClazz) {
        XStream x = new XStream();
        x.registerConverter(new DateConverter("yyyy-MM-dd HH:mm:ss",
                null, TimeZone.getTimeZone("GMT+8")));

        //不使用默认的类加载器，需要手动设置类加载器
        x.setClassLoader(beanClazz.getClassLoader());
        x.processAnnotations(beanClazz);
        x.allowTypesByRegExp(new String[]{".*"});
        // 开起注解功能
        x.autodetectAnnotations(true);
        // 忽律未知字段
        x.ignoreUnknownElements();
        return x;
    }
}
